package handler

import (
	"context"
	"github.com/astaxie/beego/logs"
	"github.com/garyburd/redigo/redis"
	"ihome/utils"

	"github.com/micro/go-micro/util/log"

	getSession "ihome/proto/getSession"
)

type GetSession struct{}

// Call is a single request handler called via client.Call or the generated client code
func (e *GetSession) SrvGetSession(ctx context.Context, req *getSession.Request, rsp *getSession.Response) error {
	logs.Info("获取session信息 GetSession /api/v1.0/session")

	rsp.Code = utils.RecodeOk
	rsp.Msg = utils.RecodeText(rsp.Code)

	bm, err := utils.NewCache()
	if err != nil {
		logs.Info("redis连接失败", err)
		rsp.Code = utils.RecodeDberr
		rsp.Msg = utils.RecodeText(rsp.Code)
		return nil
	}

	username := bm.Get(req.SessionId + "name")
	if username == nil {
		logs.Info("获取用户数据不存在", err)
		rsp.Code = utils.RecodeDberr
		rsp.Msg = utils.RecodeText(rsp.Code)
		return nil
	}

	logs.Info(req.SessionId)
	rsp.UserName, err = redis.String(username, nil)
	if err != nil {
		logs.Info("获取用户缓存失败", err)
		rsp.Code = utils.RecodeDberr
		rsp.Msg = utils.RecodeText(rsp.Code)
		return nil
	}
	logs.Info(rsp.UserName)

	return nil
}

// Stream is a server side stream handler called via client.Stream or the generated client code
func (e *GetSession) Stream(ctx context.Context, req *getSession.StreamingRequest, stream getSession.GetSession_StreamStream) error {
	log.Logf("Received GetSession.Stream request with count: %d", req.Count)

	for i := 0; i < int(req.Count); i++ {
		log.Logf("Responding: %d", i)
		if err := stream.Send(&getSession.StreamingResponse{
			Count: int64(i),
		}); err != nil {
			return err
		}
	}

	return nil
}

// PingPong is a bidirectional stream handler called via client.Stream or the generated client code
func (e *GetSession) PingPong(ctx context.Context, stream getSession.GetSession_PingPongStream) error {
	for {
		req, err := stream.Recv()
		if err != nil {
			return err
		}
		log.Logf("Got ping %v", req.Stroke)
		if err := stream.Send(&getSession.Pong{Stroke: req.Stroke}); err != nil {
			return err
		}
	}
}
